package com.cleaner.base.utils;

import android.content.Context;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.android.installreferrer.api.InstallReferrerClient;
import com.android.installreferrer.api.InstallReferrerStateListener;
import com.android.installreferrer.api.ReferrerDetails;

import java.util.HashMap;


public class InstallChannel {
    public static void referrer(@NonNull Context context, @NonNull Listener listener) {
        InstallReferrerClient installReferrerClient = InstallReferrerClient.newBuilder(context).build();
        installReferrerClient.startConnection(new InstallReferrerStateListener() {
            @Override
            public void onInstallReferrerSetupFinished(int responseCode) {
                switch (responseCode) {
                    case InstallReferrerClient.InstallReferrerResponse.OK:
                        try {
                            ReferrerDetails referrerDetails = installReferrerClient.getInstallReferrer();
                            String referrer = referrerDetails.getInstallReferrer();
                            HashMap<String, Object> params = new HashMap<>();
                            params.put("value", referrer);
                            Events.sendEvent("InstallReferrer", params);

                            if (!TextUtils.isEmpty(referrer)) {
                                setSpecial(context, referrer, listener);
                            } else {
                                listener.onFailure();
                            }

                        } catch (RemoteException e) {
                            Events.sendEvent("InstallReferrerFailure", new EventObject("msg", e.getMessage()));
                            listener.onFailure();
                        } finally {
                            installReferrerClient.endConnection();
                        }
                        break;
                    case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED:
                        Events.sendEvent("InstallReferrerNotSupported");
                        listener.onFailure();
                        break;
                    case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE:
                        Events.sendEvent("InstallReferrerServiceUnavailable");
                        listener.onFailure();
                        break;
                }
            }

            @Override
            public void onInstallReferrerServiceDisconnected() {

            }
        });
    }

    private static void setSpecial(@NonNull Context context, String referrer, @NonNull Listener listener) {
        String[] utmArray = referrer.split("&");
        String utm_content = null;

        for (String item : utmArray) {
            if (!item.startsWith("utm_source=")) continue;
            utm_content = item.replace("utm_source=", "");
            break;
        }

        //utm_content字段不为空，并且用户手机拥有Sim卡则为买量用户
        if (TextUtils.isEmpty(utm_content)) {
            Events.sendEvent("utm_source_is_empty", new EventObject("utm_source", utm_content));
            listener.onSuccess(false);
            return;
        }

        if (!hasSimCard(context)) {
            Events.sendEvent("no_sim_card");
            listener.onSuccess(false);
            return;
        }

        if (utm_content != null && utm_content.contains("am")) {
            Events.sendEvent("referrer_utm_content");
            listener.onSuccess(true);
        } else {
            listener.onSuccess(false);
        }
    }

    public interface Listener {
        default void onSuccess(boolean special) {
        }

        default void onFailure() {
        }
    }

    private static boolean hasSimCard(@NonNull Context context) {
        TelephonyManager telMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        if (simState == TelephonyManager.SIM_STATE_ABSENT) {
            result = false; // 没有SIM卡
        } else if (simState == TelephonyManager.SIM_STATE_UNKNOWN) {
            result = false;
        }
        return result;
    }

}